package com.atguigu.flink.chapter08;

import com.atguigu.flink.bean.AdsClickLog;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.text.SimpleDateFormat;
import java.time.Duration;

public class Flink05_Project_High_Ads {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        SingleOutputStreamOperator<String> main = env
                .readTextFile("input/AdClickLog.csv")
                .map(new MapFunction<String, AdsClickLog>() {
                    @Override
                    public AdsClickLog map(String value) throws Exception {
                        String[] data = value.split(",");
                        return new AdsClickLog(
                                Long.valueOf(data[0]),
                                Long.valueOf(data[1]),
                                data[2],
                                data[3],
                                Long.parseLong(data[4]) * 1000
                        );
                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<AdsClickLog>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((log, ts) -> log.getTimestamp())
                )
                .keyBy(log -> log.getUserId() + "_" + log.getAdsId())
                .process(new KeyedProcessFunction<String, AdsClickLog, String>() {

                    private ValueState<String> yesterdayState;
                    private ValueState<Boolean> warnState;
                    private ReducingState<Long> countState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        countState = getRuntimeContext()
                                .getReducingState(
                                        new ReducingStateDescriptor<Long>(
                                                "countState",
                                                Long::sum,
                                                Long.class
                                        ));

                        warnState = getRuntimeContext().getState(new ValueStateDescriptor<Boolean>("warnState", Boolean.class));

                        yesterdayState = getRuntimeContext().getState(new ValueStateDescriptor<String>("yesterdayState", String.class));
                    }

                    @Override
                    public void processElement(AdsClickLog value, Context ctx, Collector<String> out) throws Exception {
                        // 解决数据跨天： 第二天应该把状态清空
                        String yesterday = yesterdayState.value();
                        String today = new SimpleDateFormat("yyyy-MM-dd").format(value.getTimestamp());
                        if (!today.equals(yesterday)) {
                            countState.clear();
                            warnState.clear();
                            yesterdayState.update(today);
                        }

                        // 如果已经加入过了黑名单, 则不需要对这个用户对这个广告的点击进行计算
                        if (warnState.value() == null) {
                            countState.add(1L);
                        }

                        String msg = "用户: " + value.getUserId() + ", 对广告: " + value.getAdsId() + " 的点击量是: " + countState.get();

                        if (countState.get() > 99) {
                            if (warnState.value() == null) {
                                ctx.output(new OutputTag<String>("blackList") {}, msg + " 超过了阈值， 加入了黑名单");
                                warnState.update(true);
                            }
                        } else {
                            out.collect(msg);
                        }
                    }
                });

        main.print("main");
        main.getSideOutput(new OutputTag<String>("blackList") {}).print("black");

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
